'use strict';

const Service = require('egg').Service;
const fs = require('fs');
const path = require('path');
const xlsx = require('xlsx');
class IdleItemService extends Service {
  async create(data) {
    const { ctx } = this;

    // // 生成编码
    // if (!data.code) {
    //   const type = data.type === '物资' ? 'M' : 'E';
    //   const date = moment().format('YYYYMMDD');
    //   const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
    //   data.code = `${type}${date}${random}`;
    // }

    // let item = await this.ctx.model.IdleItem.findOne({
    //   where: {
    //     [this.app.Sequelize.Op.or]: [
    //       { code: data.code },
    //       { name: data.name },
    //     ]
    //   },
    //   raw: true
    // })
    // if (item) {
    //   throw new Error('编码或者名称重复')
    //   return
    // }
    // 根据category_id 或者category_name查询分类
    if (data.category_id || data.category_name) {
      let category = await this.ctx.model.IdleCategory.findOne({
        where: {
          [this.app.Sequelize.Op.or]: [
            { id: data.category_id },
            { name: data.category_name },
          ]
        },
        raw: true
      })
      data.category_id = category.id;
      data.category_name = category.name;
    } else {
      data.category_id = 0
      data.category_name = ''
    }

    return await ctx.model.IdleItem.create(data);
  }

  async update(id, data) {
    const { ctx } = this;
    const item = await ctx.model.IdleItem.findByPk(id);
    if (!item) {
      ctx.throw(404, '物资/设备不存在');
    }
    return await item.update(data);
  }
  async updateIdleItemStatus(id) {
    const { ctx } = this;
    const item = await ctx.model.IdleItem.findByPk(id);
    if (!item) {
      throw new Error('数据不存在')
    }
    return this.update(id, {
      is_public: item.is_public ? 0 : 1
    })
  }
  async deleteById(id) {
    const { ctx } = this;
    const item = await ctx.model.IdleItem.findByPk(id);
    if (!item) {
      ctx.throw(404, '物资/设备不存在');
    }

    // 检查是否有关联的调拨记录
    const transferCount = await ctx.model.IdleTransfer.count({
      where: { item_id: id }
    });
    if (transferCount > 0) {
      ctx.throw(400, '该物资/设备有调拨记录，不能删除');
    }

    return await item.destroy();
  }

  async findOne(id) {
    const { ctx } = this;
    return await ctx.model.IdleItem.findByPk(id, {
      include: [{
        model: ctx.model.IdleCategory
      },
        {
          model: ctx.model.User,
          as: 'createUser'
        }]
    });
  }

  async getPage(where, page, size) {
    const { ctx } = this;
    if (this.ctx.query.create_user_id) {
      const user = await this.ctx.model.User.findByPk(this.ctx.query.create_user_id);
      if (user) {
        // 判断用户类型
        if (user.level == 2){
          delete where.create_user_id
        }
      }
    }
    const { count, rows } = await ctx.model.IdleItem.findAndCountAll({
      where,
      offset: (page - 1) * size,
      limit: size,
      order: [['create_time', 'DESC']],
      include: [
        {
          model: ctx.model.IdleCategory,
          attributes: ['id', 'name', 'type', 'sub_type']
        },
        {
          model: ctx.model.User,
          as: 'createUser'
        }
      ]
    });
    return { count, rows };
  }

  async allList(where) {
    const { ctx } = this;
    return await ctx.model.IdleItem.findAll({
      where,
      order: [['create_time', 'DESC']],
      include: [{
        model: ctx.model.IdleCategory,
        attributes: ['id', 'name', 'type', 'sub_type']
      },
        {
          model: ctx.model.User,
          as: 'createUser'
        }]
    });
  }

  async simpleList(where) {
    const { ctx } = this;
    return await ctx.model.IdleItem.findAll({
      where,
      attributes: ['id', 'code', 'name', 'specification', 'unit', 'quantity', 'condition', 'status', 'province', 'city'],
      order: [['create_time', 'DESC']]
    });
  }

  async getNearby(longitude, latitude, distance, query) {
    const { ctx } = this;
    // 这里简化处理，实际应该使用地理位置计算
    // 可以使用数据库的地理位置函数或第三方服务
    const where = this.getWhereFromQuery(query);

    // 按省市筛选作为"附近"的简化实现
    const { province, city } = query;
    if (province) {
      where.province = province;
    }
    if (city) {
      where.city = city;
    }

    return await ctx.model.IdleItem.findAll({
      where,
      order: [['create_time', 'DESC']],
      include: [{
        model: ctx.model.IdleCategory,
        attributes: ['id', 'name', 'type', 'sub_type']
      },
        {
          model: ctx.model.User,
          as: 'createUser'
        }]
    });
  }

  async incrementViewCount(id) {
    const { ctx } = this;
    const item = await ctx.model.IdleItem.findByPk(id);
    if (!item) {
      ctx.throw(404, '物资/设备不存在');
    }

    return await item.increment('view_count');
  }

  async batchImportFile(file) {
    const { ctx } = this;
    const filePath = file.filepath;

    try {
      const workbook = xlsx.readFile(filePath);
      const sheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[sheetName];
      const data = xlsx.utils.sheet_to_json(worksheet);

      const result = {
        total: data.length,
        success: 0,
        fail: 0,
        errors: []
      };

      for (const item of data) {
        try {
          // 查找或创建分类
          let category = await ctx.model.IdleCategory.findOne({
            where: {
              name: item['分类'],
              type: item['类型'] === '物资' ? '物资' : '设备'
            }
          });

          if (!category) {
            category = await ctx.model.IdleCategory.create({
              name: item['分类'],
              type: item['类型'] === '物资' ? '物资' : '设备',
              parent_id: 0
            });
          }

          // 创建物资/设备
          await this.create({
            name: item['物资设备名称'],
            category_id: category.id,
            type: item['类型'] === '物资' ? '物资' : '设备',
            specification: item['规格型号'],
            unit: item['计量单位'],
            quantity: item['数量'],
            condition: item['技术状况'] ? parseInt(item['技术状况']) : 10,
            status: 'available',
            province: item['所在地'].split('-')[0] || '',
            city: item['所在地'].split('-')[1] || '',
            address: item['所在地'],
            project_id: item['归属单位ID'] || 0,
            project_name: item['归属单位'],
            unit_price: item['单位原值'] || 0,
            total_price: item['总原值'] || 0,
            discount_rate: item['折扣率'] || 100,
            rental_price: item['租售价格'] || 0,
            remark: item['备注'],
            create_user_id: ctx.state.user.id,
            create_user_name: ctx.state.user.name
          });

          result.success++;
        } catch (err) {
          result.fail++;
          result.errors.push({
            row: data.indexOf(item) + 2,
            message: err.message,
            data: item
          });
        }
      }

      return result;
    } catch (err) {
      ctx.throw(400, '导入失败：' + err.message);
    } finally {
      // 删除临时文件
      fs.unlinkSync(filePath);
    }
  }
  async bathDelete(idList) {
    const { ctx } = this;
    const result = await ctx.model.IdleItem.destroy({
      where: {
        id: {
          [this.app.Sequelize.Op.in]: idList
        }
      }
    });
    return result
  }
  async batchImportJson(items) {
    const { ctx } = this;

    const result = {
      total: items.length,
      success: 0,
      fail: 0,
      errors: []
    };

    for (let i = 0; i < items.length; i++) {
      const item = items[i];
      try {
        // 查找分类
        // let categoryId = item.category_id;
        // if (!categoryId && item.category_name) {
        //   const category = await ctx.model.IdleCategory.findOne({
        //     where: {
        //       name: item.category_name,
        //       type: item.type || '物资'
        //     }
        //   });
        //
        //   if (category) {
        //     categoryId = category.id;
        //   } else {
        //     // 创建新分类
        //     const newCategory = await ctx.model.IdleCategory.create({
        //       name: item.category_name,
        //       type: item.type || '物资',
        //       parent_id: 0
        //     });
        //     categoryId = newCategory.id;
        //   }
        // }
        //
        // if (!categoryId) {
        //   throw new Error('分类不存在');
        // }

        // 处理地址信息
        let province = item.province || '';
        let city = item.city || '';
        // 创建物资/设备
        await this.create({
          name: item.name,
          code: item.code,
          type: item.type || '物资',
          category_id: item.category_id || 0,
          category_name: item.category_name || '',
          specification: item.specification,
          unit: item.unit,
          quantity: item.quantity || 1,
          condition: item.condition || 100,
          status: item.status || 'available',
          province,
          city,
          address: item.address,
          project_id: item.project_id || 0,
          project_name: item.project_name,
          unit_price: item.unit_price || 0,
          total_price: item.total_price,
          discount_rate: item.discount_rate || 100,
          rental_price: item.rental_price || 0,
          remark: item.remark,
          create_user_id: ctx.query.create_user_id,
          create_user_name: ctx.query.create_user_name
        });

        result.success++;
      } catch (err) {
        result.fail++;
        result.errors.push({
          row: i + 1,
          message: err.message,
          data: item
        });
      }
    }

    return result;
  }

  async getExcelTemplate() {
    const templatePath = path.join(__dirname, '../public/templates/idle_item_template.xlsx');
    return fs.readFileSync(templatePath);
  }


  /**
   *
   *   router.get('/api/idleItem/userStats', controller.idleItem.getUserDeviceStats);
   *   router.get('/api/idleItem/systemStats', controller.idleItem.getSystemDeviceStats);
   *   router.get('/api/idleTransfer/stats', controller.idleItem.getTransferStats);
   */
  async getUserDeviceStats(userId, type) {
    if (!userId) {
      return  {
        totalDevices: 0,
        totalValue: 0,
        transferOutCount: 0,
        transferOutValue: 0,
        transferInCount: 0,
        transferInValue: 0
      }
    }
    let typeWhere ={

    }
    if (type) {
      typeWhere = {
        type
      }
    }
    // 发布设备总数、调出设备总数、调入设备总数
    const itemList = await this.ctx.model.IdleItem.findAll({
      where: {
        create_user_id: userId,
        ...typeWhere
      },
    })
    // 调出设备 approved_user_id = userId 调出，apply_user_id = userId 调入
    const transferItemList = await this.ctx.model.IdleTransfer.findAll({
      where: {
        [this.app.Sequelize.Op.or]: [
          { approved_user_id: userId },
          { apply_user_id: userId }
        ],
        ...typeWhere,
        status: 'approved'
      },
      include: [
        {
          model: this.ctx.model.IdleItem,
        }
      ],
    })
    let items = itemList.map(item => item.dataValues)
    let transferItems = transferItemList.map(item => item.dataValues)
    return {
      items,
      transferItems,
      totalDevices: items.reduce((pre,next) => pre + next.quantity, 0),
      totalValue: items.map(item => {
        return item.quantity * item.unit_price
      }).reduce((pre,next) => pre + next, 0),
      transferOutCount: transferItems.filter(item => item.approved_user_id === Number(userId)).reduce((pre,next) => pre + next.quantity, 0),
      transferOutValue: transferItems.filter(item => item.approved_user_id === Number(userId)).map(item => {
        if (item.idle_item && item.idle_item.unit_price){
          return item.quantity * item.idle_item.unit_price
        }
        return 0
      }).reduce((pre,next) => pre + next, 0),
      transferInCount: transferItems.filter(item => item.apply_user_id === Number(userId)).reduce((pre,next) => pre + next.quantity, 0),
      transferInValue: transferItems.filter(item => item.apply_user_id === Number(userId)).map(item => {
        if (item.idle_item && item.idle_item.unit_price){
          return item.quantity * item.idle_item.unit_price
        }
        return 0
      }).reduce((pre,next) => pre + next, 0),
    }
  }

  async getSystemDeviceStats(type) {
    let typeWhere = {}
    if (type) {
      typeWhere = {
        type
      }
    }
    // 发布设备总数、调出设备总数、调入设备总数
    const items = await this.ctx.model.IdleItem.findAll({
      raw: true,
      where: typeWhere
    })
    return {
      totalDevices: items.reduce((pre,next) => pre + next.quantity, 0),
      totalValue: items.map(item => {
        return item.quantity * item.unit_price
      }).reduce((pre,next) => pre + next, 0)
    }
  }

  async getTransferStats(startDate, endDate, type) {
    let typeWhere = {}
    if (type) {
      typeWhere = {
        type
      }
    }
    // 调出设备 approved_user_id = userId 调出，apply_user_id = userId 调入
    const transferItemList = await this.ctx.model.IdleTransfer.findAll({
      include: [
        {
          model: this.ctx.model.IdleItem,
        }
      ],
      where: {
        create_time: {
          // [Op.between]: [startDate, endDate]
          [this.app.Sequelize.Op.gte]: startDate,
          [this.app.Sequelize.Op.lte]: endDate
        },
        ...typeWhere,
        status: 'approved'
      }
    })
    let transferItems = transferItemList.map(item => item.dataValues)
    return {
      transferOutCount: transferItems.reduce((pre,next) => pre + next.quantity, 0),
      transferOutValue: transferItems.map(item => {
        if (item.idle_item && item.idle_item.unit_price){
          return item.quantity * item.idle_item.unit_price
        }
        return 0
      }).reduce((pre,next) => pre + next, 0),
    }

  }
  async getMyItems(userId, query) {
    const { ctx } = this;
    const where = this.getWhereFromQuery(query);
    where.create_user_id = userId;

    return await this.getPage(where, query.pageNum || 1, query.pageSize || 10);
  }

  getWhereFromQuery(query) {
    const where = {};
    const { name, type, category_id, province, city, condition, status, project_id } = query;

    if (name) {
      where.name = {
        [this.app.Sequelize.Op.like]: `%${name}%`,
      };
    }
    if (type) {
      where.type = type;
    }
    if (category_id) {
      where.category_id = category_id;
    }
    if (province) {
      where.province = province;
    }
    if (city) {
      where.city = city;
    }
    if (condition) {
      where.condition = condition;
    }
    if (status) {
      where.status = status;
    }
    if (project_id) {
      where.project_id = project_id;
    }

    return where;
  }

  pageOrder() {
    const { createTimeSort } = this.ctx.query
    if (createTimeSort) {
      return [
        'create_time', createTimeSort
      ]
    }
  }
}

module.exports = IdleItemService;
